#include <stdlib.h>
#include <string.h>
#include <stdio.h>

#include <glib.h>

#include "kylin-verify.h"

#define LICENSE_GROUP_STR "[license]\n"
#define LICENSE_GROUP "license"


/*
 * license_delimiter_convert, convert LICENSE file contents with new_delimiter and old_delimiter
 */
static void license_delimiter_convert (char* license_data, gsize size, char old_delimiter, char new_delimiter)
{
	int i = 0;
	int find = 0;

	if(license_data)
	{	
		char* p = license_data;

		for(i = 0; i < size; ++i)
		{
			if(!find && (p[i] == old_delimiter))
			{
				p[i] = new_delimiter;
				find = 1;
			}
			if(p[i] == '\n')
				find = 0;
		}
	}
}

/*
 * license_convert_to_keyfile, convert LICENSE file contents to the format of a key file
 */
GKeyFile* license_convert_to_keyfile(char* license_data, gsize size, char old_delimiter, char new_delimiter)
{
	char* copied_data = NULL;
	int grp_length;

	char* whole_data = NULL;
	GKeyFile* key_file = NULL;
	GKeyFileFlags flags;
	GError *error = NULL;
	gboolean res;

	copied_data = (char*)malloc(size);
	if(!copied_data)
		return NULL;

	memcpy(copied_data, license_data, size);

	license_delimiter_convert (copied_data, size, old_delimiter, new_delimiter);
	grp_length = strlen(LICENSE_GROUP_STR);

	whole_data = (char*)malloc(grp_length + size);
	if(!whole_data)
	{
		free(copied_data);
		return NULL;
	}
	memcpy(whole_data, LICENSE_GROUP_STR, grp_length);
	memcpy(&whole_data[grp_length], copied_data, size);


	key_file = g_key_file_new();
	flags = G_KEY_FILE_KEEP_COMMENTS | G_KEY_FILE_KEEP_TRANSLATIONS;

	res = g_key_file_load_from_data (key_file, whole_data, grp_length + size, flags, &error);
	if(!res)
	{
		g_key_file_free(key_file);
		free(copied_data);
		free(whole_data);

		return NULL;
	}

	free(copied_data);
	free(whole_data);

	return key_file;
}


#if 0
int main(int argc, char** argv)
{
	char* license = "TO:abc\nTERM:none\nSERIAL:1234567\n";
	GKeyFile* key_file;

	key_file = license_convert_to_keyfile(license, strlen(license), ':', '=');

	printf("%s\n", key_file_get_value(key_file, LICENSE_GROUP, "TO"));
	printf("%s\n", key_file_get_value(key_file, LICENSE_GROUP, "TERM"));
	printf("%s\n", key_file_get_value(key_file, LICENSE_GROUP, "SERIAL"));

	key_file_set_value(key_file, LICENSE_GROUP, "TO", "hahaha");
	key_file_set_value(key_file, LICENSE_GROUP, "TERM", "you guess");
	key_file_set_value(key_file, LICENSE_GROUP, "SERIAL", "67890");

	printf("%s\n", key_file_get_value(key_file, LICENSE_GROUP, "TO"));
	printf("%s\n", key_file_get_value(key_file, LICENSE_GROUP, "TERM"));
	printf("%s\n", key_file_get_value(key_file, LICENSE_GROUP, "SERIAL"));

	g_key_file_free(key_file);
	return 0;
}
#endif
